import React, { useState, useEffect, useRef, useCallback } from 'react';
import { 
  Card, 
  Typography, 
  Input, 
  Button, 
  List, 
  Avatar, 
  Space, 
  Dropdown, 
  Menu, 
  Modal, 
  message, 
  Spin,
  Empty,
  Tag,
  Popconfirm
} from 'antd';
import './ChatPage.css';
import { marked } from 'marked';
import { 
  SendOutlined, 
  RobotOutlined, 
  UserOutlined, 
  MoreOutlined, 
  DeleteOutlined, 
  DownloadOutlined,
  PlusOutlined,
  MessageOutlined,
  BulbOutlined
} from '@ant-design/icons';
import { useAuth } from '../store/AuthContext';
import { aiService } from '../services/api';

// 配置marked，禁用段落标签
marked.setOptions({
  breaks: true,
  gfm: true
});

const { Text, Title } = Typography;
const { TextArea } = Input;

interface Message {
  id: number;
  role: 'user' | 'assistant';
  content: string;
  created_at: string;
}

interface Conversation {
  id: number;
  title: string;
  created_at: string;
  updated_at: string;
}

const AIChat: React.FC = () => {
  const { isAuthenticated, user } = useAuth();
  
  // 添加CSS样式来修复markdown渲染问题
  const aiMessageStyles = `
    .ai-message-content {
      margin: 0 !important;
      padding: 0 !important;
      display: block !important;
      width: 100% !important;
      box-sizing: border-box !important;
      font-size: 14px !important;
      line-height: 1.4 !important;
    }
    .ai-message-content * {
      margin: 0 !important;
      padding: 0 !important;
      box-sizing: border-box !important;
    }
    .ai-message-content p {
      margin: 0 !important;
      padding: 0 !important;
      display: block !important;
      line-height: 1.4 !important;
      font-size: 14px !important;
    }
    .ai-message-content p:not(:last-child) {
      margin-bottom: 8px !important;
    }
    .ai-message-content p:last-child {
      margin-bottom: 0 !important;
    }
    .ai-message-content h1, .ai-message-content h2, .ai-message-content h3, 
    .ai-message-content h4, .ai-message-content h5, .ai-message-content h6 {
      margin: 0 0 8px 0 !important;
      padding: 0 !important;
    }
    .ai-message-content ul, .ai-message-content ol {
      margin: 0 0 8px 0 !important;
      padding-left: 20px !important;
    }
    .ai-message-content li {
      margin: 0 !important;
    }
    .ai-message-content code {
      background: rgba(0,0,0,0.1) !important;
      padding: 2px 4px !important;
      border-radius: 3px !important;
      font-size: 0.9em !important;
    }
    .ai-message-content pre {
      margin: 0 0 8px 0 !important;
      padding: 8px !important;
      background: rgba(0,0,0,0.05) !important;
      border-radius: 4px !important;
      overflow-x: auto !important;
    }
    .ai-message-content pre:last-child {
      margin-bottom: 0 !important;
    }
    .ai-message-content blockquote {
      margin: 0 0 8px 0 !important;
      padding-left: 16px !important;
      border-left: 3px solid #ccc !important;
    }
    .ai-message-content blockquote:last-child {
      margin-bottom: 0 !important;
    }
  `;
  const [conversations, setConversations] = useState<Conversation[]>([]);
  const [currentConversation, setCurrentConversation] = useState<Conversation | null>(null);
  const [messages, setMessages] = useState<Message[]>([]);
  const [inputValue, setInputValue] = useState('');
  const [loading, setLoading] = useState(false);
  const [suggestions, setSuggestions] = useState<string[]>([]);
  const [suggestionsLoading, setSuggestionsLoading] = useState(false);
  const [aiThinking, setAiThinking] = useState(false);
  const [deleteModalVisible, setDeleteModalVisible] = useState(false);
  const [conversationToDelete, setConversationToDelete] = useState<Conversation | null>(null);
  const [deleteAllModalVisible, setDeleteAllModalVisible] = useState(false);
  const [deleteAllLoading, setDeleteAllLoading] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // 加载对话列表
  const loadConversations = async () => {
    try {
      console.log('开始加载对话列表...');
      const response = await aiService.getConversations() as any;
      console.log('对话列表响应:', response);
      if (response.success) {
        setConversations(response.data);
        // 如果有对话，选择最新的一个
        if (response.data.length > 0) {
          setCurrentConversation(response.data[0]);
        }
      } else {
        console.error('对话列表响应格式错误:', response);
        message.error('加载对话列表失败');
      }
    } catch (error) {
      console.error('加载对话列表失败:', error);
      message.error('加载对话列表失败: ' + ((error as any)?.message || '未知错误'));
    }
  };

  // 加载消息
  const loadMessages = async (conversationId: number) => {
    try {
      const response = await aiService.getMessages(conversationId) as any;
      if (response.success) {
        setMessages(response.data);
      }
    } catch (error) {
      console.error('加载消息失败:', error);
    }
  };

  // 加载推荐问题
  const loadSuggestions = async (conversationId?: number) => {
    try {
      setSuggestionsLoading(true);
      let response;
      
      if (conversationId) {
        // 获取基于对话内容的智能建议
        response = await aiService.getSmartSuggestions(conversationId) as any;
      } else {
        // 获取默认建议
        response = await aiService.getSuggestions() as any;
      }
      
      if (response.success && response.data && response.data.length > 0) {
        setSuggestions(response.data);
      } else {
        // 如果API没有返回建议，使用默认建议
        setSuggestions([
          '请帮我写一个Python函数',
          '解释一下什么是机器学习',
          '如何优化网站性能',
          '推荐一些学习资源'
        ]);
      }
    } catch (error) {
      console.error('加载推荐问题失败:', error);
      // 出错时也使用默认建议
      setSuggestions([
        '请帮我写一个Python函数',
        '解释一下什么是机器学习',
        '如何优化网站性能',
        '推荐一些学习资源'
      ]);
    } finally {
      setSuggestionsLoading(false);
    }
  };

  // 创建新对话
  const createConversation = useCallback(async () => {
    try {
      console.log('开始创建新对话...');
      setLoading(true);
      const response = await aiService.createConversation() as any;
      console.log('创建对话响应:', response);
      if (response.success) {
        const newConversation = {
          id: response.data.id,
          title: response.data.title,
          created_at: new Date().toISOString(),
          updated_at: new Date().toISOString()
        };
        setConversations(prev => [newConversation, ...prev]);
        setCurrentConversation(newConversation);
        // 加载新对话的消息
        await loadMessages(newConversation.id);
        message.success('新对话已创建');
      } else {
        console.error('创建对话响应格式错误:', response);
        message.error('创建对话失败');
      }
    } catch (error) {
      console.error('创建对话失败:', error);
      message.error('创建对话失败: ' + ((error as any)?.message || '未知错误'));
    } finally {
      setLoading(false);
    }
  }, []);

  // 生成对话标题
  const generateConversationTitle = async (messages: Message[]) => {
    try {
      console.log('开始生成对话标题，消息数量:', messages.length);
      console.log('当前对话ID:', currentConversation?.id);
      
      // 获取用户的第一条消息和AI的第一条回答
      const firstUserMessage = messages.find(msg => msg.role === 'user');
      const firstAiMessage = messages.find(msg => msg.role === 'assistant');
      
      if (!firstUserMessage) {
        console.log('未找到用户消息');
        return;
      }

      const userContent = firstUserMessage.content.trim();
      const aiContent = firstAiMessage?.content.trim() || '';
      
      // 构建标题生成提示
      const titlePrompt = `请根据以下对话内容生成一个简洁的标题，要求：
1. 标题长度不超过10个字符
2. 准确概括对话主题
3. 使用中文

用户问题：${userContent}
AI回答：${aiContent.substring(0, 200)}...

请只返回标题，不要其他内容：`;

      console.log('调用AI生成标题...');
      
      // 调用AI服务生成标题
      const titleResponse = await aiService.generateTitle(titlePrompt) as any;
      let title = '';
      
      if (titleResponse.success && titleResponse.data) {
        title = titleResponse.data.title || titleResponse.data.content || titleResponse.data;
        // 清理标题，移除可能的引号和其他符号
        title = title.replace(/['"]/g, '').trim();
        // 确保不超过10个字符
        if (title.length > 10) {
          title = title.substring(0, 10);
        }
      } else {
        // 如果AI生成失败，使用用户消息的前10个字符作为备选
        title = userContent.length > 10 ? userContent.substring(0, 10) : userContent;
        console.log('AI生成标题失败，使用备选标题:', title);
      }

      console.log('生成的标题:', title);
      console.log('当前对话列表:', conversations);

      // 更新对话标题
      const updatedConversations = conversations.map(conv => 
        conv.id === currentConversation?.id 
          ? { ...conv, title }
          : conv
      );
      console.log('更新后的对话列表:', updatedConversations);
      setConversations(updatedConversations);
      
      // 更新当前对话
      if (currentConversation) {
        const updatedCurrentConversation = { ...currentConversation, title };
        console.log('更新当前对话:', updatedCurrentConversation);
        setCurrentConversation(updatedCurrentConversation);
      }
      
      // 调用API更新后端对话标题
      try {
        if (currentConversation?.id) {
          console.log('调用API更新后端对话标题，ID:', currentConversation.id, '标题:', title);
          await aiService.updateConversationTitle(currentConversation.id, title);
          console.log('后端对话标题已更新');
        }
      } catch (error) {
        console.error('更新后端对话标题失败:', error);
      }
      
      console.log('对话标题已更新');
    } catch (error) {
      console.error('生成对话标题失败:', error);
    }
  };

  // 点击建议问题发送消息
  const handleSuggestionClick = (suggestion: string) => {
    setInputValue(suggestion);
    // 直接发送消息
    sendMessageWithText(suggestion);
  };

  // 发送指定文本的消息
  const sendMessageWithText = async (messageText: string) => {
    if (!messageText.trim() || !currentConversation) {
      return;
    }

    const userMessage = messageText.trim();
    setInputValue('');

    // 添加用户消息到界面
    const newUserMessage: Message = {
      id: Date.now(),
      role: 'user',
      content: userMessage,
      created_at: new Date().toISOString()
    };
    setMessages(prev => [...prev, newUserMessage]);

    // 显示AI正在思考
    setAiThinking(true);

    try {
      const response = await aiService.sendMessage(currentConversation.id, userMessage) as any;

      if (response.success) {
        // 添加AI回复到界面
        const aiMessage: Message = {
          id: Date.now() + 1,
          role: 'assistant',
          content: response.data.aiResponse,
          created_at: new Date().toISOString()
        };

        // 添加AI消息到界面
        setMessages(prev => {
          const newMessages = [...prev, aiMessage];

          // 如果对话标题还是默认标题，则生成新标题
          if (currentConversation?.title === '新对话' || currentConversation?.title === 'New Conversation') {
            const allMessages = [...messages, newUserMessage, aiMessage];
            generateConversationTitle(allMessages);
          }

          return newMessages;
        });

        // 重新加载建议问题（延迟一点时间确保消息已保存）
        setTimeout(() => {
          loadSuggestions(currentConversation.id);
        }, 500);
      }
    } catch (error) {
      console.error('发送消息失败:', error);
      message.error('发送消息失败');
    } finally {
      setAiThinking(false);
    }
  };

  // 发送消息
  const sendMessage = async () => {
    console.log('=== sendMessage 开始 ===');
    console.log('inputValue:', inputValue);
    console.log('currentConversation:', currentConversation);
    
    if (!inputValue.trim() || !currentConversation || aiThinking) {
      console.log('sendMessage 提前返回');
      return;
    }

    const userMessage = inputValue.trim();
    console.log('用户消息内容:', userMessage);
    setInputValue('');

    // 添加用户消息到界面
    const newUserMessage: Message = {
      id: Date.now(),
      role: 'user',
      content: userMessage,
      created_at: new Date().toISOString()
    };
    setMessages(prev => [...prev, newUserMessage]);

    // 显示AI正在思考
    setAiThinking(true);

    try {
      console.log('开始调用AI服务...');
      
      
      const response = await aiService.sendMessage(currentConversation.id, userMessage) as any;
      console.log('AI服务响应:', response);
      
      if (response.success) {
        console.log('AI回答成功，开始处理...');
        // 添加AI回复到界面
        const aiMessage: Message = {
          id: Date.now() + 1,
          role: 'assistant',
          content: response.data.aiResponse,
          created_at: new Date().toISOString()
        };
        console.log('创建的AI消息:', aiMessage);
        
        // 添加AI消息到界面
        setMessages(prev => {
          const newMessages = [...prev, aiMessage];
          console.log('更新后的消息列表:', newMessages);
          console.log('消息详情:', newMessages.map(msg => ({ role: msg.role, content: msg.content.substring(0, 20) + '...' })));
          console.log('AI消息数量:', newMessages.filter(msg => msg.role === 'assistant').length);

          // 如果对话标题还是默认标题，则生成新标题
          if (currentConversation?.title === '新对话' || currentConversation?.title === 'New Conversation') {
            console.log('=== 检测到默认标题，开始生成标题 ===');
            console.log('当前标题:', currentConversation?.title);
            console.log('用户消息:', newUserMessage);
            console.log('AI消息:', aiMessage);
            // 立即生成标题，使用完整的消息列表
            const allMessages = [...messages, newUserMessage, aiMessage];
            console.log('完整消息列表:', allMessages);
            generateConversationTitle(allMessages);
          } else {
            console.log('对话标题已存在，跳过标题生成');
            console.log('当前对话标题:', currentConversation?.title);
          }

          return newMessages;
        });

        // 重新加载建议问题（延迟一点时间确保消息已保存）
        setTimeout(() => {
          loadSuggestions(currentConversation.id);
        }, 500);
      }
    } catch (error) {
      console.error('发送消息失败:', error);
      message.error('发送消息失败');
    } finally {
      setAiThinking(false);
    }
  };

  // 删除对话
  const handleDeleteConversation = async (conversationId: number) => {
    console.log('开始删除对话:', conversationId);
    try {
      const response = await aiService.deleteConversation(conversationId) as any;
      console.log('删除响应:', response);
      if (response && response.success) {
        message.success('对话已删除');
        setConversations(prev => prev.filter(c => c.id !== conversationId));
        if (currentConversation?.id === conversationId) {
          setCurrentConversation(null);
          setMessages([]);
        }
      } else {
        message.error('删除失败');
      }
    } catch (error: any) {
      console.error('删除对话失败:', error);
      message.error('删除对话失败: ' + (error.message || '未知错误'));
    }
  };

  // 导出对话
  const exportConversation = async (conversationId: number) => {
    console.log('exportConversation 函数被调用，对话ID:', conversationId);
    try {
      const response = await aiService.exportConversation(conversationId);
      const blob = new Blob([response.data || response], { type: 'text/plain;charset=utf-8' });
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      // 使用对话标题作为文件名，如果没有标题则使用默认名称
      const conversation = conversations.find(c => c.id === conversationId);
      const fileName = conversation?.title || `AI对话_${conversationId}`;
      a.download = `${fileName}.txt`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
      message.success('对话已导出');
    } catch (error) {
      console.error('导出对话失败:', error);
      message.error('导出对话失败');
    }
  };

  // 删除所有对话
  const handleDeleteAllConversations = async () => {
    console.log('开始删除所有对话');
    setDeleteAllLoading(true);
    try {
      // 逐个删除所有对话
      for (const conversation of conversations) {
        try {
          await aiService.deleteConversation(conversation.id);
        } catch (error) {
          console.error(`删除对话 ${conversation.id} 失败:`, error);
        }
      }
      
      // 清空本地状态
      setConversations([]);
      setCurrentConversation(null);
      setMessages([]);
      
      message.success('所有对话已删除');
    } catch (error: any) {
      console.error('删除所有对话失败:', error);
      message.error('删除所有对话失败: ' + (error.message || '未知错误'));
    } finally {
      setDeleteAllLoading(false);
    }
  };

  // 滚动到底部
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(() => {
    if (isAuthenticated) {
      loadConversations();
      loadSuggestions();
    }
  }, [isAuthenticated]);

  useEffect(() => {
    if (currentConversation) {
      loadMessages(currentConversation.id);
      // 加载基于当前对话的智能建议
      loadSuggestions(currentConversation.id);
    }
  }, [currentConversation]);

  useEffect(() => {
    scrollToBottom();
  }, [messages]);


  // 如果用户未认证，显示登录提示
  if (!isAuthenticated) {
    return (
      <div style={{ 
        display: 'flex', 
        alignItems: 'center', 
        justifyContent: 'center', 
        height: 'calc(100vh - 120px)',
        flexDirection: 'column',
        gap: '16px'
      }}>
        <Empty 
          description="请先登录以使用AI对话功能"
          image={Empty.PRESENTED_IMAGE_SIMPLE}
        />
        <Button 
          type="primary" 
          onClick={() => window.location.href = '/login'}
        >
          去登录
        </Button>
      </div>
    );
  }


  return (
    <div className="ai-chat-page-container" style={{ 
      background: 'transparent',
      height: 'calc(100vh - 40px)', // 减去Layout的padding
      overflow: 'hidden'
    }}>
      <style>{aiMessageStyles}</style>
      <div style={{ display: 'flex', height: '100%' }}>
        {/* 左侧对话列表 */}
        <div style={{ 
          width: '300px', 
          borderRight: '1px solid #f0f0f0',
          display: 'flex',
          flexDirection: 'column'
        }}>
          {/* 头部 */}
          <div style={{ 
            padding: '16px', 
            borderBottom: '1px solid #f0f0f0',
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center'
          }}>
            <Title level={4} style={{ margin: 0 }}>AI对话</Title>
            <Space>
              <Button 
                danger
                size="small"
                loading={deleteAllLoading}
                onClick={() => {
                  if (conversations.length === 0) {
                    message.warning('没有对话可删除');
                    return;
                  }
                  setDeleteAllModalVisible(true);
                }}
              >
                {deleteAllLoading ? '删除中...' : '删除全部'}
              </Button>
              <Button 
                type="primary" 
                icon={<PlusOutlined />} 
                onClick={createConversation}
                loading={loading}
                size="small"
              >
                新对话
              </Button>
            </Space>
          </div>
          
          {/* 对话列表 */}
          <div style={{ 
            flex: 1, 
            overflowY: 'auto',
            padding: '8px'
          }}>
            {conversations.length === 0 ? (
              <div style={{ 
                display: 'flex', 
                alignItems: 'center', 
                justifyContent: 'center', 
                height: '100%' 
              }}>
                <Empty description="暂无对话" />
              </div>
            ) : (
              <List
                dataSource={conversations}
                renderItem={(conversation) => (
                  <List.Item
                    style={{
                      cursor: 'pointer',
                      backgroundColor: currentConversation?.id === conversation.id ? '#e6f7ff' : 'transparent',
                      padding: '12px 8px',
                      borderRadius: '6px',
                      marginBottom: '4px',
                      border: currentConversation?.id === conversation.id ? '1px solid #1890ff' : '1px solid transparent'
                    }}
                    onClick={() => setCurrentConversation(conversation)}
                  >
                    <List.Item.Meta
                      avatar={<Avatar icon={<MessageOutlined />} size="small" />}
                      title={
                        <div style={{ 
                          fontSize: '14px', 
                          fontWeight: currentConversation?.id === conversation.id ? 'bold' : 'normal',
                          overflow: 'hidden',
                          textOverflow: 'ellipsis',
                          whiteSpace: 'nowrap'
                        }}>
                          {conversation.title}
                        </div>
                      }
                      description={
                        <div style={{ 
                          fontSize: '12px', 
                          color: '#666',
                          overflow: 'hidden',
                          textOverflow: 'ellipsis',
                          whiteSpace: 'nowrap'
                        }}>
                          {new Date(conversation.updated_at).toLocaleString('zh-CN')}
                        </div>
                      }
                    />
                  </List.Item>
                )}
              />
            )}
          </div>
        </div>

        {/* 右侧聊天区域 */}
        <div style={{ 
          flex: 1, 
          display: 'flex', 
          flexDirection: 'column',
          background: '#fff'
        }}>
          {currentConversation ? (
            <>
              {/* 聊天标题栏 */}
              <div style={{
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                padding: '16px',
                borderBottom: '1px solid #f0f0f0',
                backgroundColor: '#fafafa'
              }}>
                <div>
                  <Title level={4} style={{ margin: 0 }}>
                    {currentConversation.title}
                  </Title>
                  <Text style={{ color: '#666' }}>
                    AI对话
                  </Text>
                </div>
                <Space>
                  <Button
                    icon={<DownloadOutlined />}
                    onClick={() => {
                      console.log('导出按钮被点击，对话ID:', currentConversation.id);
                      exportConversation(currentConversation.id);
                    }}
                  >
                    导出对话
                  </Button>
                  <Button
                    danger
                    icon={<DeleteOutlined />}
                    onClick={() => {
                      console.log('删除按钮被点击，对话ID:', currentConversation.id);
                      setConversationToDelete(currentConversation);
                      setDeleteModalVisible(true);
                    }}
                  >
                    删除对话
                  </Button>
                </Space>
              </div>

              {/* 消息列表 */}
              <div style={{ 
                flex: 1, 
                overflowY: 'auto', 
                padding: '16px',
                background: '#fafafa',
                display: 'flex',
                justifyContent: 'center'
              }}>
                {messages.length === 0 ? (
                  <div style={{ 
                    textAlign: 'center', 
                    padding: '60px 20px',
                    display: 'flex',
                    flexDirection: 'column',
                    alignItems: 'center',
                    justifyContent: 'center',
                    height: '100%'
                  }}>
                    <Empty description="开始与AI对话吧！" />
                  </div>
                ) : (
                  <div style={{ 
                    paddingBottom: '20px',
                    maxWidth: '800px',
                    width: '100%'
                  }}>
                    {messages.map((message) => (
                      <div
                        key={message.id}
                        style={{
                          display: 'flex',
                          justifyContent: message.role === 'user' ? 'flex-end' : 'flex-start',
                          marginBottom: '16px',
                          padding: '0 8px'
                        }}
                      >
                        <div
                          style={{
                            maxWidth: '75%',
                            display: 'flex',
                            flexDirection: message.role === 'user' ? 'row-reverse' : 'row',
                            alignItems: message.role === 'user' ? 'flex-start' : 'flex-start',
                            gap: '8px'
                          }}
                        >
                          <Avatar
                            icon={message.role === 'user' ? <UserOutlined /> : <RobotOutlined />}
                            size="small"
                            style={{
                              backgroundColor: message.role === 'user' ? '#1890ff' : '#52c41a',
                              flexShrink: 0,
                              marginTop: message.role === 'assistant' ? '-4px' : '0'
                            }}
                          />
                          {message.role === 'user' ? (
                            <div
                              style={{
                                backgroundColor: '#1890ff',
                                color: 'white',
                                padding: '10px 14px',
                                borderRadius: '18px 18px 4px 18px',
                                wordBreak: 'break-word',
                                lineHeight: '1.4',
                                boxShadow: '0 1px 2px rgba(0,0,0,0.1)',
                                textAlign: 'left',
                                whiteSpace: 'pre-wrap'
                              }}
                            >
                              {message.content}
                            </div>
                          ) : (
                            <div
                              style={{
                                flex: 1,
                                padding: '0 8px',
                                lineHeight: '1.4',
                                fontSize: '14px',
                                color: '#333',
                                textAlign: 'left'
                              }}
                            >
                              <div 
                                dangerouslySetInnerHTML={{ __html: marked.parse(message.content) as string }}
                                className="ai-message-content"
                              />
                            </div>
                          )}
                        </div>
                      </div>
                    ))}
                    {aiThinking && (
                      <div
                        style={{
                          display: 'flex',
                          justifyContent: 'flex-start',
                          marginBottom: '16px',
                          padding: '0 8px'
                        }}
                      >
                        <div
                          style={{
                            maxWidth: '75%',
                            display: 'flex',
                            flexDirection: 'row',
                            alignItems: 'flex-start',
                            gap: '8px'
                          }}
                        >
                          <Avatar
                            icon={<RobotOutlined />}
                            size="small"
                            style={{
                              backgroundColor: '#52c41a',
                              flexShrink: 0,
                              marginTop: '-4px'
                            }}
                          />
                          <div
                            style={{
                              flex: 1,
                              padding: '0 8px',
                              lineHeight: '1.4',
                              fontSize: '14px',
                              color: '#999',
                              fontStyle: 'italic'
                            }}
                          >
                            thinking...
                          </div>
                        </div>
                      </div>
                    )}
                    <div ref={messagesEndRef} />
                  </div>
                )}
                
              </div>

              {/* 推荐问题 */}
              {messages.length === 0 && suggestions.length > 0 && (
                <div style={{ 
                  padding: '0 16px 16px 16px',
                  borderTop: '1px solid #f0f0f0'
                }}>
                  <Text type="secondary" style={{ fontSize: '14px' }}>你可能想问：</Text>
                  <div style={{ marginTop: '8px', display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
                    {suggestions.map((suggestion, index) => (
                      <Tag
                        key={index}
                        style={{ 
                          margin: 0,
                          cursor: 'pointer',
                          borderRadius: '16px',
                          padding: '4px 12px',
                          fontSize: '12px'
                        }}
                        onClick={() => setInputValue(suggestion)}
                      >
                        {suggestion}
                      </Tag>
                    ))}
                  </div>
                </div>
              )}

              {/* 建议问题区域 */}
              {suggestions.length > 0 && (
                <div style={{
                  padding: '12px 16px',
                  borderTop: '1px solid #f0f0f0',
                  backgroundColor: '#fafafa',
                  display: 'flex',
                  justifyContent: 'center'
                }}>
                  <div style={{ 
                    maxWidth: '800px',
                    width: '100%'
                  }}>
                    <div style={{ 
                      fontSize: '12px', 
                      color: '#666', 
                      marginBottom: '8px',
                      display: 'flex',
                      alignItems: 'center',
                      gap: '4px'
                    }}>
                      <BulbOutlined />
                      猜你想问
                      {suggestionsLoading && <Spin size="small" />}
                    </div>
                    <div style={{ 
                      display: 'flex', 
                      flexWrap: 'nowrap', 
                      gap: '8px',
                      overflow: 'hidden'
                    }}>
                    {suggestions.slice(0, 4).map((suggestion, index) => (
                      <Button
                        key={index}
                        size="small"
                        type="text"
                        onClick={() => handleSuggestionClick(suggestion)}
                        disabled={aiThinking}
                        style={{
                          borderRadius: '16px',
                          border: '1px solid #d9d9d9',
                          backgroundColor: aiThinking ? '#f5f5f5' : '#fff',
                          color: aiThinking ? '#bfbfbf' : '#666',
                          fontSize: '12px',
                          height: '28px',
                          padding: '0 12px',
                          whiteSpace: 'nowrap',
                          overflow: 'hidden',
                          textOverflow: 'ellipsis',
                          flex: '0 0 auto',
                          minWidth: '0',
                          maxWidth: '180px'
                        }}
                        onMouseEnter={(e) => {
                          if (!aiThinking) {
                            e.currentTarget.style.borderColor = '#1890ff';
                            e.currentTarget.style.color = '#1890ff';
                          }
                        }}
                        onMouseLeave={(e) => {
                          if (!aiThinking) {
                            e.currentTarget.style.borderColor = '#d9d9d9';
                            e.currentTarget.style.color = '#666';
                          }
                        }}
                      >
                        {suggestion}
                      </Button>
                    ))}
                    {suggestions.length > 4 && (
                      <Button
                        size="small"
                        type="text"
                        disabled={aiThinking}
                        style={{
                          borderRadius: '16px',
                          border: '1px solid #d9d9d9',
                          backgroundColor: aiThinking ? '#f5f5f5' : '#fff',
                          color: aiThinking ? '#bfbfbf' : '#999',
                          fontSize: '12px',
                          height: '28px',
                          padding: '0 12px',
                          whiteSpace: 'nowrap',
                          flex: '0 0 auto',
                          minWidth: '0',
                          maxWidth: '40px'
                        }}
                      >
                        ...
                      </Button>
                    )}
                    </div>
                  </div>
                </div>
              )}

              {/* 输入区域 */}
              <div style={{ 
                padding: '16px',
                borderTop: '1px solid #f0f0f0',
                backgroundColor: '#fff',
                display: 'flex',
                justifyContent: 'center'
              }}>
                <Space.Compact style={{ width: '100%', maxWidth: '800px' }}>
                  <TextArea
                    value={inputValue}
                    onChange={(e) => setInputValue(e.target.value)}
                    placeholder="输入你的问题..."
                    autoSize={{ minRows: 1, maxRows: 4 }}
                    onPressEnter={(e) => {
                      if (e.shiftKey) return;
                      e.preventDefault();
                      sendMessage();
                    }}
                    style={{
                      borderRadius: '20px 0 0 20px',
                      border: '1px solid #d9d9d9'
                    }}
                  />
                  <Button
                    type="primary"
                    icon={<SendOutlined />}
                    onClick={sendMessage}
                    disabled={!inputValue.trim() || aiThinking}
                    loading={aiThinking}
                    style={{
                      borderRadius: '0 20px 20px 0',
                      height: 'auto',
                      minHeight: '32px'
                    }}
                  >
                    {aiThinking ? '发送中...' : '发送'}
                  </Button>
                </Space.Compact>
              </div>
            </>
          ) : (
            <div style={{ 
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              height: '100%',
              flexDirection: 'column',
              gap: '16px'
            }}>
              <Empty 
                description="选择一个对话开始聊天"
                image={Empty.PRESENTED_IMAGE_SIMPLE}
              />
              <Button 
                type="primary" 
                icon={<PlusOutlined />} 
                onClick={createConversation}
                loading={loading}
              >
                创建新对话
              </Button>
            </div>
          )}
        </div>
      </div>

      {/* 删除确认Modal */}
      <Modal
        title="确认删除"
        open={deleteModalVisible}
        onOk={() => {
          console.log('确认删除', conversationToDelete?.id);
          if (conversationToDelete) {
            handleDeleteConversation(conversationToDelete.id);
          }
          setDeleteModalVisible(false);
          setConversationToDelete(null);
        }}
        onCancel={() => {
          setDeleteModalVisible(false);
          setConversationToDelete(null);
        }}
        okText="删除"
        cancelText="取消"
        okType="danger"
        centered
      >
        <p>确定要删除与{conversationToDelete ? conversationToDelete.title : ''}的对话吗？</p>
        <p style={{ color: '#999', fontSize: '14px' }}>删除后无法恢复</p>
      </Modal>

      {/* 删除所有对话确认Modal */}
      <Modal
        title="确认删除所有对话"
        open={deleteAllModalVisible}
        onOk={() => {
          console.log('确认删除所有对话');
          handleDeleteAllConversations();
          setDeleteAllModalVisible(false);
        }}
        onCancel={() => {
          setDeleteAllModalVisible(false);
        }}
        okText="删除全部"
        cancelText="取消"
        okType="danger"
        centered
      >
        <p>确定要删除所有对话吗？</p>
        <p style={{ color: '#999', fontSize: '14px' }}>此操作将删除所有对话记录，删除后无法恢复</p>
        <p style={{ color: '#ff4d4f', fontSize: '14px', fontWeight: 'bold' }}>共 {conversations.length} 个对话将被删除</p>
      </Modal>
    </div>
  );
};

export default AIChat;
